package com.tang.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatis工具类
 * 封装了mybatis从构建工厂获取的对象的过程，直接可调用getSqlSession()即可获取session对象。
 * ***需要手动释放资源
 * **已默认提交事务
 */
public class MyBatisUtils {
    //将sqlSessionFactory提升作用域
    public static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "MyBatisConfig.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }

}
